import {
	asyncRouterMap,
	constantRouterMap
} from "@/router"
import Vue from 'vue'
import {
	getMenubyUser
} from '@/api/index'

function deepCopy(data) {
	const t = typeOf(data)
	let o

	if (t === 'array') {
		o = []
	} else if (t === 'object') {
		o = {}
	} else {
		return data
	}

	if (t === 'array') {
		for (let i = 0; i < data.length; i++) {
			o.push(deepCopy(data[i]))
		}
	} else if (t === 'object') {
		for (let i in data) {
			o[i] = deepCopy(data[i])
		}
	}
	return o
}
/**
 * 过滤账户是否拥有某一个权限，并将菜单从加载列表移除
 *
 * @param permission
 * @param route
 * @returns {boolean}
 */
function hasPermission(permslist, route) {
	if (route.meta && route.meta.permission) {

		let flag = false;
		if (route.meta.permission.includes('home')) {
			return true
		}
		console.log(route.meta.permission);
		for (let i = 0, len = permslist.length; i < len; i++) {
			flag = route.meta.permission.includes(permslist[i])
			if (flag) {
				return true
			}
		}
		return false
	}
	return true
}

function setAsyncRouter(routerMap) {
	let accessedRouters = []
	routerMap.forEach(route => {
		let path = route.url;
		let component = '';
		if (route.component && (route.component.indexOf('http') > -1 || route.component.indexOf('https') > -
				1)) {
			component = 'components/Myiframe/index.vue';
			path = route.component;
			// console.log(path);
		} else {
			if (route.type == 0) {
				component = 'layouts/BasicLayout.vue'
			} else {
				component = route.component || 'components/404/index.vue';
			}
		}
		if (route && (route.type == 1 || route.type == 0)) {
			let namelist = route.url.split('/');
			let name = route.name
			let newroute = {
				path: route.url,
				name: name,
				redirect: route.redirect,
				component: resolve => require(['../../' + component], resolve),
				hidden: route.isHiddenInMenu == 1,
				meta: {
					title: route.title,
					icon: route.icon,
					url: path,
					permissionList: route.perms,
					keepAlive: route.isCacheRoute == 1,
					hidden: route.isHiddenInMenu == 1
				}
			}
			if (route.children && route.children.length > 0) {
				newroute.children = [...setAsyncRouter(route.children)];
				if (newroute.children.some(item => !item.hidden)) {
					newroute.hideChildrenInMenu = false
				} else {
					newroute.hideChildrenInMenu = true
				}
				if (route.redirect == 'redirect') {
					for (var i = 0; i < route.children.length; i++) {
						if (route.children[i].type == 1 || route.children[i].type == 0) {
							newroute.redirect = route.children[i].url;
							break;
						}
					}
				}
			}
			accessedRouters.push(newroute)
		}
	})
	return accessedRouters
}
/* 将多维数组拍成二维数组。解决多级路由无法缓存的问题 */
const formatRouter = (routes, newRoutes = []) => {
	routes.map(item => {
		if (item.children && item.children.length > 0) formatRouter(item.children, newRoutes);
		if (item.name == 'EmptyRouteView') {
			newRoutes.push(item.children);
		} else {
			newRoutes.push(item);
		}
	})
	return newRoutes;
}


const permission = {
	state: {
		routers: constantRouterMap,
		addRouters: [],
		buttenpremissions: [],
		menuId: '',
		hasGetMenu: false
	},
	mutations: {
		SET_ROUTERS: (state, routers) => {
			state.routers = constantRouterMap.concat(routers);
			/* 在这里将roter 变成最多二级 */
			let flatRoutes = routers.map(item => {
				let info = {
					...item
				};
				if (info.children && info.children.length > 0) {
					let children = formatRouter(info.children);
					info.children = children;
				}
				return info
			})
			state.addRouters = [...flatRoutes]
		},
		SET_PERMSLIST: (state, permslist) => {
			state.permslist = permslist;
			sessionStorage.setItem('buttenpremissions', JSON.stringify(permslist))
		},
		SET_menuId: (state, menuId) => {
			state.menuId = menuId;
		},
		SET_menuState: (state, menustate) => {
			state.hasGetMenu = menustate;
		},


	},
	actions: {
		GenerateRoutes({
			commit
		}) {
			return new Promise((resolve, reject) => {
				getMenubyUser().then((da) => {
					let menulist = da.data;
					let permslist = '';
					let router = [];
					menulist.unshift({
						"title": "初始页，默认隐藏",
						"url": "/",
						"perms": null,
						"component": null,
						"redirect": null,
						"isCacheRoute": null,
						"type": 0,
						"icon": "home",
						"orderNum": 1,
						"isHiddenInMenu": 1,
						"children": null
					});
					/* 获取权限列表 */
					permslist = JSON.stringify(menulist).match(/(?=\"perms\":")([^\,]*)(?=\,)/g)
						.join(',').replace(
							/"perms":/g,
							'').replace(/\"/g, '').split(',');

					const accessedRouters = setAsyncRouter(menulist);
					/* 先获取第一个，将首页指向这个路由 */
					let homeIndex = accessedRouters.findIndex(item => item.path == '/');
					let homeredirect = '/usercenter';
					if (accessedRouters && accessedRouters.length > 1) {
						for (var i = 0; i < accessedRouters.length; i++) {
							if (accessedRouters[i].path !== '/') {
								homeredirect = accessedRouters[i].path;
								break;
							}
						}
					}
					accessedRouters[homeIndex].redirect = homeredirect
					router = [].concat(accessedRouters);
					router.push({
						path: '*',
						redirect: '/404',
						hidden: true
					})
					commit('SET_ROUTERS', router);
					commit('SET_PERMSLIST', permslist);
					commit('SET_menuState', true);
					resolve()
				}).catch(e => {
					reject();
				})

			})
		}
	},


}

export default permission
